import { s_getcommontableinfo, s_getSelectData, s_getTableInfo, s_produce_updateInfo, s_stockIn, s_stockOut } from "@/services/basis";
import { YahooFilled } from "@ant-design/icons";
import { ActionType, EditableFormInstance, EditableProTable, heILIntl, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormDateRangePicker, ProFormDigit, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProTable } from "@ant-design/pro-components";
import { Button, Col, message, Modal, Row, Space } from "antd";
import { random } from "lodash";
import moment from "moment";
import { Item } from "rc-menu";
import { useRef, useState } from "react";
// import styles from 'index.less';

const App:React.FC=()=>{
     const [quantityTotal,setQuantityTotal]=useState(0);
     const [boxTotal,setBoxTotal]=useState(0);
     const [tdata,setTdata]=useState<any[]>([]);   
     const [open,setOpen]=useState(false);                        

     const formRef_main=useRef<ProFormInstance>();
     const editableRef=useRef<EditableFormInstance>();
     const actionRef=useRef<ActionType>();
     const formRef_query=useRef<ProFormInstance>();
    
     const [columns,setColumns]=useState<ProColumns[]>([
              {dataIndex:'sku',title:'SKU',width:'8%',
                  onCell:(record:any, index:any, text:any)=>{
                     if(index==0)
                          return {style:{color:'red',fontSize:20}};
                      else
                          return {style:{color:'red',fontSize:20}};
                   }},
              {dataIndex:'fncode',title:'FNCODE',width:'8%',
                  onCell:()=>{return {style:{color:'red',fontSize:20}};}
               }]);

     //保存装箱记录----------------------------------------
     async function saveBoxing(){
        if(tdata.length==0||formRef_main.current?.getFieldValue('quantity_total')==undefined
              ||formRef_main.current?.getFieldValue('box_total')==undefined)
              message.warning('没有装箱数据，不能保存');
        else{
        var fdata=formRef_main.current?.getFieldsValue();
        fdata={...fdata,deliverdate:moment(moment(fdata.deliverdate).toDate()).format('YYYY-MM-DD HH:mm:ss')};
            // alert(JSON.stringify(fdata));
         var ntdata=new Array();
         // alert(JSON.stringify(tdata));
         if(tdata.length>0){
            var tkeys=Object.keys(tdata[0]);
            tdata.map((item:any)=>{
                 tkeys.forEach((it)=>{
                    var obj:any=new Object();
                     // obj['sku']=item.sku;
                     obj['material_id']=item.material_id;
                     if(item.sku!='汇总'&&it!='sku'&&it!='fncode'&&item[it]){
                          obj['box_sno']=it;
                          obj['quantity']=item[it];
                          ntdata.push(obj);
                     };
                 });
            }); 
         };
         
         alert(JSON.stringify(ntdata));
         // source,x_id,operater_id,etype,fdata
         const x=await s_produce_updateInfo({source:'boxing',x_id:1,operater_id:1,
                         fdata:{fdata,tdata:ntdata}});
         if(x.success){
            // alert(x.data[0][0].mid);
            formRef_main.current?.setFieldsValue({etype:0,id:x.data[0][0].mid});
            
            message.success('保存成功');
            }
         else
            message.error('失败，请联系管理员');
        };
     };

     //查询历史装箱记录，进行修改或补箱----------------------------
     async function queryBoxing(){
         setOpen(true);
     };

     //执行查询
     async function query(){
        var  fdata=formRef_query.current?.getFieldsValue();
        fdata={...fdata,
               begindate:(fdata.begindate==undefined||fdata.begindate==null)?null
                          :moment(moment(fdata.begindate).toDate()).format('YYYY-MM-DD'),
               enddate:(fdata.enddate==undefined||fdata.enddate==null)?null
                          :moment(moment(fdata.enddate).toDate()).format('YYYY-MM-DD'),
              }; 

      //   alert(JSON.stringify(fdata));
      //  x_id,cate_id,id,source,fdata
       const x:any=await s_getcommontableinfo({x_id:1,cate_id:[],id:0,source:'boxing',fdata});
       if(x.success){
            // alert(JSON.stringify(x.data[0]));
            if(x.data[0]&&x.data[0].length>0){
                  //  动态创建表结构
                    var newcol:ProColumns[]=[{ dataIndex:'sku',title:'SKU',width:'8%',
                     onCell:(record:any, index:any, text:any)=>{
                        if(index==0)
                             return {style:{color:'red',fontSize:20}};
                         else
                             return {style:{color:'red',fontSize:20}};
                      }},
                      {dataIndex:'fncode',title:'FNCODE',width:'8%',
                          onCell:()=>{return {style:{color:'red',fontSize:20}};}
                    }];
                  //   alert(JSON.stringify(x.data[2][0].temp));
                    var temp=JSON.parse(x.data[2][0].temp);               
                    temp.map((item:any)=>{
                       newcol.push({dataIndex:item,title:item,width:50,
                        onCell:(record:any, index:any, text:any)=>(index==0?{style:{color:'red',fontSize:20}}:{})});
                    });
                  //   设置列
                    setColumns(newcol);
                  //   设置表头汇总
                    formRef_main.current?.setFieldsValue({ ...x.data[0][0] });
                    setBoxTotal(x.data[0][0].box_total);
                    setQuantityTotal(x.data[0][0].quantity_total);
                    //设置表体明细--先添加汇总行
                    //按箱号（列名）计算汇总数量-------
                    var f=x.data[1];
                    var keys:any[]=[];
                    newcol.map((item3:any)=>{
                      keys.push(item3.dataIndex);
                    });
                    var newobj:any=new Object();
                    newobj['sku']='汇总';
                    newobj['fncode']='';
                    f.map((item:any)=>{
                        keys.forEach((key)=>{
                              if(key!='sku'&&key!='fncode')
                                  newobj[key]=(newobj[key]?newobj[key]:0)+(item[key]?item[key]:0);
                           });
                    });

                    setTdata([newobj,...f]);
                  //   setTdata(x.data[1]);
                message.success('查询成功');
             };
       }else
          message.warning('没有找到装箱数据');
        
     };

   //   装箱生成销售出库单-------
   async function stockOutBoxing(){
       if(tdata.length==0)
            message.warning('没有装箱数据，不能出库');
       else if(formRef_main.current?.getFieldValue('status')==2)
           message.warning('装箱单已出库，请先删除出库单，再重新出库。');
       else if(formRef_main.current?.getFieldValue('custom_id')==undefined
               ||formRef_main.current?.getFieldValue('warehouse_id'==undefined))
          message.warning('客户和仓库都不能为空');
       else{
          var fdata=formRef_main.current?.getFieldsValue();
          fdata={...fdata,org_id:1,outtype_id:7};
          var ntdata:any=[];
          var tkeys=Object.keys(tdata[0]);
          tdata.map((item:any)=>{
               tkeys.forEach((it)=>{
                  var obj:any=new Object();
                   // obj['sku']=item.sku;
                   obj['material_id']=item.material_id;
                   if(item.sku!='汇总'&&it!='sku'&&it!='fncode'&&item[it]){
                        obj['box_sno']=it;
                        obj['quantity']=item[it];
                        ntdata.push(obj);
                   };
               });
          }); 


          //调用出库函数
         //  x_id,operater_id,etype,source,JSON.stringify(tdata)
          const x=await s_stockOut({x_id:1,operater_id:1,etype:formRef_main.current?.getFieldValue('status'),
                         source:'boxing',tdata:{fdata,tdata:ntdata}});
          if(x.success){
            message.success('出库成功');
            formRef_main.current?.setFieldValue('status',2);
          }else
            message.error('保存失败，请联系管理员');

       };
   };

   //=============================================================================================================
     return <>
    <ProCard style={{height:760,overflow:'auto'}}>
    <ProForm submitter={false} labelAlign='left' labelCol={{offset:0,span:7}} layout="horizontal"
        style={{fontSize:50}} formRef={formRef_main}
        initialValues={{status:1}}
    >
       <Row gutter={8}>
         <Col span={4}>
           <Space.Compact>
               <Button style={{fontSize:30,height:50}}>箱码</Button>
               <ProFormDigit name='box'   width={80}  
                 fieldProps={{
                      style:{fontSize:30,height:50} ,
                      onBlur:(value:any)=>{
                     //  onKeyDown:(e:any)=>{
                        // alert(JSON.stringify(e));
                        if(value>0){
                           // var v=e.target.value;
                           var t=columns.filter((item:any)=>item.dataIndex==value); 
                           // alert(t.length);
                           if(t&&t.length==0){
                              //总箱数递增
                              setBoxTotal(boxTotal+1);
                              formRef_main.current?.setFieldValue('box_total',boxTotal+1);
                              //界面动态添加列
                              setColumns([...columns,{dataIndex:value,title:value,width:50,
                                 onCell:(record:any, index:any, text:any)=>(index==0?{style:{color:'red',fontSize:20}}:{})}]);
                           };
                        };
                     }, 
                   }} 
                 />
           </Space.Compact>
         </Col>
         <Col span={4}>
             <Space.Compact>
                <Button style={{fontSize:30,height:50}}>数量</Button>
                <ProFormDigit name='quantity' width={80} min={-100}
                   fieldProps={{
                          style:{fontSize:30,height:50},
                          
                    }}  />
           </Space.Compact>
         </Col>
         <Col span={5}>
             <Space.Compact>
                  <Button style={{height:50,fontSize:30,color:'red'}}>SKU扫码</Button>  
                  <ProFormText name='qrcode'   width={200}  
                       fieldProps={{
                            style:{fontSize:30, height:50}, 
                            onKeyDown:(e:any)=>{
                               if(e.key=='Enter'&&e.target.value!=undefined){
                                 var vin=e.target.value;
                                 // 扫入的码包含三部分：id_code_fncode，需拆解
                                 var p1=vin.indexOf('_');
                                 var material_id=vin.substring(0,p1);
                                 // alert(p1);
                                 var sku=vin.substring(p1+1,vin.indexOf('_',p1+1));
                                 // alert(vin.indexOf('_',p1+1))
                                 var fncode=vin.substring(vin.indexOf('_',vin.indexOf('_',p1+1))+1);
                                 // alert(vin.indexOf('_',vin.indexOf('_',p1+1)));

                                 // alert(material_id+'+'+sku+'+'+fncode);

                                 var box=formRef_main.current?.getFieldValue('box');
                                 var quantity=formRef_main.current?.getFieldValue('quantity');
                                 var newdata:any[]=[];
                                 if(box==undefined||quantity==undefined)
                                    message.warning('箱号和数量，必须填写');
                                 else{
                                    // var f=formRef_main.current?.getFieldValue('editable');
                                    // var f=editableRef.current?.getRowsData?.();
                                    var f=tdata.length>0?tdata.filter((_,index)=>index>0):[];
                                    // alert(JSON.stringify(f));
                                    var t=(f&&f.filter((item:any)=>item.sku==sku));
                                    //  alert(JSON.stringify(t));
                                    
                                    if(t==undefined||t&&t.length==0){
                                        var t1:any=new Object({sku,fncode,material_id});
                                        t1[box]=quantity;
                                        f.push(t1);

                                       newdata=f;
                                       //  setTdata(f);
                                       //  actionRef.current?.reload?.();
                                    }else{
                                        f=f.map((item:any)=>{
                                           if(item.sku==sku){
                                              item[box]=quantity+(item[box]?item[box]:0);
                                             //   alert(JSON.stringify(item));
                                               return item;
                                           }else
                                               return item;
                                        });

                                        
                                       //  actionRef2.current?.reload?.();
                                        newdata=f;
                                    };

                                    //按箱号（列名）计算汇总数量-------
                                        var keys:any[]=[];
                                        columns.map((item3:any)=>{
                                          keys.push(item3.dataIndex);
                                        });
                                        var newobj:any=new Object();
                                        newobj['sku']='汇总';
                                        newobj['fncode']='';
                                        f.map((item:any)=>{
                                            keys.forEach((key)=>{
                                                  if(key!='sku'&&key!='fncode')
                                                      newobj[key]=(newobj[key]?newobj[key]:0)+(item[key]?item[key]:0);
                                               });
                                        });
 
                                        setTdata([newobj,...newdata]);
                                        actionRef.current?.reload?.();
                                        //自动累计表头总数量
                                        setQuantityTotal(quantityTotal+quantity);
                                        formRef_main.current?.setFieldValue('quantity_total',quantityTotal+quantity);
                                 };
                            };
                          },
                }} />  
               </Space.Compact>
         </Col>
         <Col span={2}>
              <ProFormRadio.Group name='status' label='状态' 
              options={[{value:0,label:'编辑'},{value:1,label:'新增'},{value:2,label:'已出库'}]} />
         </Col>
         {/* <Col span={2}>
              <ProFormRadio.Group name='status' label='状态' 
              options={[{value:0,label:''},{value:1,label:'是'}]} />
         </Col> */}
         <Col span={7}>
           <Space>
             <Button style={{width:80,height:50,fontSize:20}} onClick={()=>saveBoxing()}>保存</Button> 
             <Button style={{width:80,height:50,fontSize:20}} onClick={()=>stockOutBoxing()}>出库</Button>
             <Button style={{width:80,height:50,fontSize:20}} onClick={()=>queryBoxing()}>查询</Button>
           </Space>
         </Col>
        
        
       </Row>
       <Row gutter={8}>
        <Col span={4}>
        <ProFormSelect name='custom_id' label='客户'    width={200} 
                        rules={[{required:true,message:'必填项'}]}
                        showSearch
                        request={async ()=>{
                              const x=await s_getSelectData({x_id:1,source:'v_custom'});
                              return x.data;}}
                    />
        </Col>
        <Col span={4}>
        <ProFormSelect name='warehouse_id' label='仓库'    width={200} 
                      rules={[{required:true,message:'必填项'}]}
                        showSearch
                        request={async ()=>{
                              const x=await s_getSelectData({x_id:1,source:'base2_ware'});
                              return x.data;}}
                    />
        </Col>
        <Col span={3}>
           <ProFormText name='deliverdate' label='发货日期' initialValue='2025-03-26' width={100}/>
        </Col>
        <Col span={3}>
           <ProFormText name='quantity_total' label='已装数量'  width={90}/>
        </Col>
        <Col span={3}>
           <ProFormText name='box_total' label='已装箱数'   width={90}/>
        </Col>
        <Col span={4}>
           <ProFormText name='memo' label='备注'   width={300}/>
           {/* <ProFormText name='id' label='ID' width={80} /> */}
        </Col>
       </Row>
          

         <ProTable
             name='editable'
             rowKey='sku'
             actionRef={actionRef}
            //  editableFormRef={editableRef}
             search={false}
             options={false}
             columns={columns}
             dataSource={tdata}
             bordered
             columnEmptyText={false}
             
            //  recordCreatorProps={false}
            //  editable={{
            //      type:'multiple',
            //  }}
            // scroll={{x:'auto'}}  
       />
      </ProForm>
      {/* 查询历史装箱记录，并可以进行修改---------------------------------------------------------- */}
       <Modal open={open} destroyOnClose onCancel={()=>setOpen(false)} onClose={()=>setOpen(false)}
           okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}} width={600}>
            <ProCard title='查询装箱单' style={{height:400}}
                extra={<Space>
                    <Button onClick={()=>query()}>开始查询</Button>
                     <Button onClick={()=>setOpen(false)}>关闭</Button>
                </Space>}
            >
               <ProForm submitter={false} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:5}}
                   formRef={formRef_query}
               >
                    <ProFormText name='vouch_code' label='装箱单号'  width={300}/>
                    <ProFormSelect name='custom_id' label='客户'    width={300} 
                        showSearch
                        request={async ()=>{
                              const x=await s_getSelectData({x_id:1,source:'v_custom'});
                              return x.data;}}
                    />
                    <ProFormDatePicker name='begindate' label='装箱起始日期' />
                    <ProFormDatePicker name='enddate' label='装箱结束日期' />
               </ProForm>
            </ProCard>
      </Modal>
      </ProCard> 
    </>;
};

export default App;

 